package com.licheedev.serialtool.util;

import com.blankj.utilcode.util.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class GpioCtlUtils {
    public static FileWriter fw;
    public static final String peth = "/sys/devices/platform/1000b000.pinctrl/mt_gpio";


    public static void setGpioHigt(String pin) {
        String str = "out " + pin + " 1";
        try {
            if (checkFileExist(peth)) {
                fw = new FileWriter(peth);
                fw.write(str);
                fw.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void setGpioLow(String pin) {
        String str = "out " + pin + " 0";
        try {
            if (checkFileExist(peth)) {
                fw = new FileWriter(peth);
                fw.write(str);
                fw.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void setGpioMode(String pin) {
        String str = "mode " + pin + " 0";
        try {
            if (checkFileExist(peth)) {
                fw = new FileWriter(peth);
                fw.write(str);
                fw.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void setGpioDir(String pin) {
        String str = "dir " + pin + " 1";
        try {
            if (checkFileExist(peth)) {
                fw = new FileWriter(peth);
                fw.write(str);
                fw.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 检查文件是否存在
     * @param path
     * @return
     */
    public static boolean checkFileExist(String path) {
        if (path == null || (path != null && path.isEmpty()))
            return false;
        File file = new File(path);
        if (file != null && file.exists()) {
            return true;
        }
        return false;
    }
}
